<?php
declare(strict_types=1);

namespace App\Admin\Controllers\Message;

use App\Admin\Actions\Message\SendMiNiTemplateAction;
use App\Constant\CacheKey;
use App\Library\SnowFlakeId;
use App\Models\Admin\Message\TemplateConfig;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;

class TemplateConfigController extends AdminController
{
    protected $title = "微信模板";

    public function grid(): Grid
    {
        $grid = new Grid(new TemplateConfig());
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->like('title', "分类名称");
                $filter->equal('is_show', "启用状态")->select([
                    1 => '启用',
                    2 => '禁用',
                ]);
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->between('created_at', "创建时间")->datetime();
                $filter->equal('template_id', "模板ID");
            });
        });
        $grid->model()->orderByDesc("id");
        $grid->column("uid", "模板编号")->copyable();
        $grid->column("title", "模板名称");
        $grid->column("template_id", "模板ID")->copyable();
        $grid->column("navigator", "跳转地址");
        $grid->column('is_show', "启用状态")->display(function ($is_show) {
            if ($is_show == 1) {
                return "<span style='color:#059B50'>启用</span>";
            }
            return "<span style='color:#E70F0FFF'>禁用</span>";
        });
        $grid->column("remark", "配置描述");
        $grid->column("created_at", "创建时间");
        $grid->disableExport();
        $grid->actions(function ($actions) {
            $actions->disableView();
            $actions->add(new SendMiNiTemplateAction());
        });
        return $grid;
    }

    public function form(): Form
    {
        $form = new Form(new TemplateConfig());
        $form->hidden("uid", "模板编号")->default(SnowFlakeId::getId());
        $form->text("title", "模板名称")->rules('required|max:20');
        $form->text("template_id", "模板ID")->rules('required|max:100');
        $form->text("navigator", "跳转地址")->help("只能设置微信小程序的页面地址");
        $form->radio("is_show", "启用状态")->options([1 => "启用", 2 => "禁用"])->default(1);
        $form->textarea("remark", "配置描述")->required();
        $form->table('values', "模板配配置", function ($table) {
            $table->text('key', "配置key")->rules('required');
            $table->text('value', "配置默认值");
            $table->select("type", "值类型")
                ->help("<a herf='https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/sendMessage.html'>微信官方文档</a>")
                ->options(CacheKey::MiNiWeChatTemplateConfig)
                ->rules("required");
            $table->text('desc', "配置描述");
        });
        return $form;
    }
}
